package org.zoomdev.zoom.dao.adapters.result;

import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.dao.adapters.ResultSetAdapter;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StringEnumResultSetAdapter implements ResultSetAdapter {

    private final Method caster;

    public StringEnumResultSetAdapter(Class<?> type) {
        try {
            caster = type.getMethod("valueOf", String.class);
        } catch (NoSuchMethodException e) {
            throw new ZoomException(e);
        }
    }

    @Override
    public Object getObject(ResultSet rs, int columnIndex) throws SQLException {
        String str = rs.getString(columnIndex);
        if (str == null) {
            return null;
        }
        try {
            return caster.invoke(null, str);
        } catch (Exception e) {
            throw new ZoomException(e);
        }
    }


}
